package edu.jd.movieplatform.user.info;

import edu.jd.movieplatform.common.CommonService;
import edu.jd.movieplatform.common.CurrentUser;
import edu.jd.movieplatform.common.Result;
import edu.jd.movieplatform.common.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/info")
public class UserInfoAPI {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CommonService commonService;

    @GetMapping("")
    public Result getUserInfo(@RequestHeader("Token")String token){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        return Result.success("success",userInfoService.getUserInfo(currentUser.getUserName()));
    }

    @PostMapping("/modify-info")
    public Result modifyUserInfo(@RequestHeader("Token")String token, @RequestBody UserInfoDto userInfoDto){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        userInfoDto.setUsername(currentUser.getUserName());
        userInfoService.modifyInfo(userInfoDto);
        return Result.success("success");
    }

    @PostMapping("/modify-password")
    public Result modifyPassword(@RequestHeader("Token")String token, @RequestBody PasswordDto passwordDto){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        boolean isok = userInfoService.checkPassword(currentUser.getUserName(), passwordDto.getOldPassword());
        if(!isok){
            return Result.fail(200, "原密码不正确");
        }else{
            userInfoService.modifyPassword(currentUser.getUserName(), passwordDto.getNewPassword());
            return Result.success("success");
        }
    }
}
